package cn.lyd.org.service.impl;

import cn.lyd.base.enm.EmpStateEnum;
import cn.lyd.base.query.BaseQuery;
import cn.lyd.base.service.impl.BaseServiceImpl;
import cn.lyd.base.until.BussinessException;
import cn.lyd.base.until.PageList;
import cn.lyd.org.domain.Department;
import cn.lyd.org.domain.Employee;
import cn.lyd.org.mapper.DepartmentMapper;
import cn.lyd.org.mapper.EmployeeMapper;
import cn.lyd.org.service.IEmployeeService;
import cn.lyd.org.vo.EmployeeRoleVo;
import cn.lyd.user.domain.Logininfo;
import cn.lyd.user.mapper.LogininfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    /**
     * 查询部门树
     * @return
     */
    @Override
    public List<Department> deptTree() {
        /*
         * 1.查询出所有的部门，放在map集合里
         * 2.遍历部门，选出没有parent_id的部门=父部门,放在部门树的集合里
         * 3.选出有parent_id的部门=子部门，找出它的父部门，把子部门放到父部门的children中
         * */
        //查询所有部门
        List<Department> all = departmentMapper.findAll();

        //放到map集合里
        Map<Long, Department> map = new HashMap<>();
        for (Department department : all){
            map.put(department.getId(),department);
        }

        //部门树集合
        List<Department> deptTree = new ArrayList<>();
        //遍历部门
        for (Department department : all){
            //选出没有parent_id的部门=顶级部门,放在部门树的集合里
            if (department.getParent_id()==null){
                deptTree.add(department);
            }
            else {
                //选出有parent_id的部门=子部门,找出它的父部门，
                Long parent_id = department.getParent_id();
                Department parentDepartment = map.get(parent_id);
                // 把子部门放到父部门的children中
                List<Department> children = parentDepartment.getChildren();
                children.add(department);

            }
        }
        System.out.println("部门树");
        System.out.println(deptTree);
        return deptTree;
    }

    /**
     * 查询某个店铺下的员工
     * @param id
     * @return
     */
    @Override
    public List<Employee> findByShopId(Long id) {
        return employeeMapper.findByShopId(id);
    }


    /**
     * 重写添加：要添加的表：logininfo表，emp表，t_employee_role表
     * @param employee
     */
    @Override
    public void add(Employee employee) {
        //1.添加t_logininfo表
            Logininfo logininfo = new Logininfo();
            logininfo.setUsername(employee.getUsername());
            logininfo.setPhone(employee.getPhone());
            logininfo.setEmail(employee.getEmail());
            //todo 盐值密码？ 设置一个默认盐值密码，发送邮件通知员工在个人中心修改密码



            logininfo.setType(EmpStateEnum.ACTIVITY_NO_PASS.getCode());//0管理员，1用户
            logininfoMapper.add(logininfo);
            //添加logininfo表后，因为设置了自增长id会返回给当前对象logininfo主键id


        //2.添加员工
            //设置logininfo_id
            employee.setLogininfo_id(logininfo.getId());
            super.add(employee);
            //因为设置了自增长id。会返回id给employee对象
            //todo 盐值密码?


        //3.添加员工和角色的中间表 t_employee_role
            //获取添加好的员工的id
            Long employeeId = employee.getId();
            //获取前端传来的角色id数组
            List<Long> roleIdList = employee.getRole_idList();//{19}
            //遍历角色id数组 添加中间表
            for (Long roleId : roleIdList) {
                employeeMapper.addEmployeeRoleTable(employeeId, roleId);
            }
    }


    /**
     * 删除员工重写：要删除的表：logininfo表，emp表，t_employee_role表
     * @param id  员工id
     */
    @Override
    public void delete(Long id) {

        //1.删除logininfo表
            //1.找到该id对应的员工
            //2.获取该员工的logininfo_id
            //3.删除该员工对应的logininfo数据
            logininfoMapper.delete(employeeMapper.findById(id).getLogininfo_id());

        //2.删除t_employee_role表  员工和角色是一对多的关系,通过employee_id删除效率更高
            employeeMapper.deletEmployeeRoleTableByEmpId(id);

        //3.删除员工
            super.delete(id);

    }


    /**
     *  分页查询重写：员工编辑时 回显角色
     * @param query
     * @return
     */
    @Override
    public PageList<Employee> queryByPage(BaseQuery<Employee> query) {

        //1.获取员工集合  [员工,员工,员工]
        List<Employee> employeeList = employeeMapper.queryByPage(query);

        //2.获取员工id集合 [员工id, 员工id, 员工id, 员工id, 员工id]
        List<Long> empIdList = employeeList.stream().map(employee ->employee.getId()).collect(Collectors.toList());

        //3.获取中间表的数据----{[员工id,角色id],[员工id,角色id],[员工id,角色id]}
        List<EmployeeRoleVo> empRoleVo = employeeMapper.findRoleIdListFromEmpRoleTableByEmpIdList(empIdList);

        /* 4.包装成map={
                    {员工id,{角色id,角色id,角色id},
                    {员工id,{角色id,角色id,角色id},
                    {员工id,{角色id,角色id,角色id},
        }
         */
        Map<Long, List<Long>> map =
                //按员工id分组
                empRoleVo.stream().collect(Collectors.groupingBy(EmployeeRoleVo::getEmployee_id,
                //取出角色id,包装成集合
                Collectors.mapping(EmployeeRoleVo::getRole_id, Collectors.toList())));

        //5.遍历员工集合，设置当前员工的角色id集合到roles
        employeeList.stream().forEach(employee -> {
            List<Long> roleIdList = map.get(employee.getId());
            employee.setRole_idList(roleIdList);
        });

        //6.调用父类分页方法
        return super.queryByPage(query);
    }


    /**
     * 修改员工重写：要修改的表：logininfo表，emp表，t_employee_role表
     * @param employee
     */
    @Override
    public void update(Employee employee) {
        //员工id不变
        //1.修改 emp表
        super.update(employee);

        //2.修改 logininfo表
            Logininfo newLogininfo = new Logininfo();
            newLogininfo.setId(employee.getLogininfo_id());
            newLogininfo.setUsername(employee.getUsername());
            newLogininfo.setPhone(employee.getPhone());
            newLogininfo.setEmail(employee.getEmail());
            //修改界面没有密码和盐值，不需要在这修改
            logininfoMapper.update(newLogininfo);

        //3.修改 t_employee_role表
            //先删除
            employeeMapper.deletEmployeeRoleTableByEmpId(employee.getId());
            //再添加
            employee.getRole_idList().stream().forEach(roleId->{
                employeeMapper.addEmployeeRoleTable(employee.getId(),roleId);
            });


    }


}
